import { Module } from 'vuex'
import { USER_STATE } from '../common/enums'
import http from '../common/request'

interface IUserInfo {
  headImage: string
  headImageThumb: string
  id: number
  nickName: string
  online: null
  sex: number
  signature: string
  type: number
  userName: string
}

export interface IUserState {
  userInfo: IUserInfo
  state: USER_STATE
}

const userStore: Module<IUserState, any> = {
  state: {
    userInfo: {} as any,
    state: USER_STATE.FREE
  },

  mutations: {
    setUserInfo(state, userInfo: IUserInfo) {
      // 使用深拷贝方式，否则小程序页面不刷新
      Object.assign(state.userInfo, userInfo)
    },
    setUserState(state, userState: USER_STATE) {
      state.state = userState
    },
    clear(state) {
      state.userInfo = {} as any
      state.state = USER_STATE.FREE
    }
  },
  actions: {
    loadUser(context) {
      return new Promise((resolve, reject) => {
        http({
          url: '/user/self',
          method: 'GET'
        })
          .then((userInfo) => {
            console.log(userInfo)
            context.commit('setUserInfo', userInfo)
            resolve(userInfo)
          })
          .catch((res) => {
            reject(res)
          })
      })
    }
  }
}

export default userStore
